import 'package:flutter/material.dart';
import 'package:test1/View/MyRowText.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Flutter_Data_SharedPreferences_Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return Flutter_Data_SharedPreferences_State();
  }
}

class Flutter_Data_SharedPreferences_State
    extends State<Flutter_Data_SharedPreferences_Page> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("SharedPreferences"),
        ),
        body: ListView(
          children: <Widget>[
            MyRowText("SharedPreferences", () async {
              SharedPreferences sharedPreferences = await SharedPreferences
                  .getInstance();
              sharedPreferences.setString(
                  "name", "xiaoming"); //没有该key是添加键值对，有该key时修改对应的值
              sharedPreferences.setString(
                  "age", "18"); //没有该key是添加键值对，有该key时修改对应的值

              for (String key in sharedPreferences.getKeys()) {
                debugPrint("所有的key分别为： $key");
              }
              debugPrint("获取存储的值：name= ${sharedPreferences.get("name")}");
              debugPrint("获取存储的值：age= ${sharedPreferences.get("age")}");

              sharedPreferences.setString("name", "lisi");

              debugPrint("获取修改后存储的值：name= ${sharedPreferences.get("name")}");

              sharedPreferences.remove("name"); //清除指定key
              debugPrint("获取删除后的值：name= ${sharedPreferences.get("name")}");

              sharedPreferences.clear(); //清除所有
              debugPrint("获取清除所有后的值：name= ${sharedPreferences.get("name")}");
            }),
          ],
        ),
      ),
    );
  }
}

/**
 * SharedPreferences轻量级存储类，以键值对的形式保存设置，属性和数据。
 * 在pubspec.yaml 导入库
 * dependencies:
    shared_preferences: ^0.5.1+1

 * sharedPreferences.setXXX(key, value);//没有该key是添加键值对，有该key时修改对应的值
 * sharedPreferences.get(key);//获取key对应的值
 * sharedPreferences.remove(key);//清除指定key
 * sharedPreferences.clear();//清除所有
 * sharedPreferences.getKeys();获取所有的key
 */